package com.example.diarymanger.controller;

import com.example.diarymanger.bean.ApiResponse;
import com.example.diarymanger.bean.DiaryBean;
import com.example.diarymanger.bean.NoteBean;
import com.example.diarymanger.config.UploadConfig;
import com.example.diarymanger.service.NoteService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;

@RequestMapping("/note")
@RestController
public class NoteController {
    @Autowired
    public NoteService noteService;
    @Autowired
    public UploadConfig uploadConfig;

    @PostMapping(value = "/saveNote", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<ApiResponse> saveNote(
            @RequestParam(value = "contentFiles", required = false) List<MultipartFile> imageLink,
            @RequestParam(value = "coverFile", required = false) MultipartFile coverFile,  // 显式接收文件

            @ModelAttribute NoteBean noteBean
    ) throws IOException {

        System.out.println("imageLink=[" + imageLink + "]");

        // 封面图片保存路径
        String coverUploadDir = "D:\\IDEA-Project\\schoolProject\\Diary-manger\\Diary-manger\\noteCoverPath";
        String imageUploadDir = "D:\\IDEA-Project\\schoolProject\\Diary-manger\\Diary-manger\\noteImagePath";

        // 确保上传目录存在
        Files.createDirectories(Paths.get(coverUploadDir));
        // 处理封面图片
        if (coverFile != null && !coverFile.isEmpty()) {
            try {
                // 获取文件名并构建保存路径
                String fileName = StringUtils.cleanPath(coverFile.getOriginalFilename());
                Path path = Paths.get(coverUploadDir, fileName);
                // 保存文件到指定路径
                Files.copy(coverFile.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
                // 构建相对文件下载URI
                String relativeFileDownloadUri = "/noteCoverPath/" + fileName;
                // 设置封面图片链接到noteBean
                noteBean.setCoverLink(relativeFileDownloadUri);
            } catch (IOException e) {
                e.printStackTrace();
                return new ResponseEntity<>(new ApiResponse(false, "Failed to upload cover image"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        if (imageLink != null && !imageLink.isEmpty()) {
            List<String> contentImageLinks = new ArrayList<>();
            for (MultipartFile image : imageLink) {
                if (!image.isEmpty()) {
                    try {
                        String fileName = StringUtils.cleanPath(image.getOriginalFilename());
                        Path path = Paths.get(imageUploadDir, fileName);
                        Files.copy(image.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
                        contentImageLinks.add("/noteImagePath/" + fileName);
                    } catch (IOException e) {
                        // 单个图片失败不影响其他图片
                        e.printStackTrace();
                    }
                }
            }
            noteBean.setImageLink(String.join(",", contentImageLinks));
        }
        // 调用服务层保存笔记
        ResponseEntity<ApiResponse> response = noteService.saveNote(noteBean);
        // 返回响应结果
        if (response.getBody().isSuccess()) {
            return new ResponseEntity<>(new ApiResponse(true, "Note saved successfully"), HttpStatus.CREATED);
        } else {
            return new ResponseEntity<>(new ApiResponse(false, "Failed to save note"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 根据用户ID获取笔记
     *
     * @param userId
     * @return
     */
    @GetMapping("/selectNoteAll")
    public ResponseEntity<List<NoteBean>> getNotesByUserId(@RequestParam Long userId) {
        return noteService.getNotesByUserId(userId);
    }

    /**
     * 根据笔记ID删除笔记
     *
     * @param noteId
     * @return
     */
    @DeleteMapping("/delete/{noteId}")
    public String deleteDiary(@PathVariable Integer noteId) {
        boolean isDeleted = noteService.deleteByNoteId(noteId);
        if (isDeleted) {
            System.out.println("删除笔记成功");
            return "删除笔记成功";
        } else {
            System.out.println("删除笔记失败");
            return "删除笔记失败";
        }
    }


    /**
     * 根据笔记ID获取笔记
     *
     * @param noteId
     * @return
     */
    @GetMapping("/selectNoteByNoteId/{noteId}")
    public ResponseEntity<NoteBean> getNoteByNoteId(@PathVariable Integer noteId) {
        try {
            NoteBean noteBean = noteService.getNoteByNoteId(noteId);
            return new ResponseEntity<>(noteBean, HttpStatus.OK);
        } catch (NoSuchElementException e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }


    @PutMapping(value = "/updateNoteByNoteId/{noteId}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> updateDiaryWithFiles(
            @PathVariable Integer noteId,
            @ModelAttribute NoteBean noteBean,
            @RequestParam(value = "tags", required = false) List<String> tags,
            @RequestParam(value = "contentFiles", required = false) List<MultipartFile> imagesLink,
            @RequestParam(value = "coverFile", required = false) MultipartFile coverFile) throws IOException {

        String coverUploadDir = "D:\\IDEA-Project\\schoolProject\\Diary-manger\\Diary-manger\\noteCoverPath";
        String imageUploadDir = "D:\\IDEA-Project\\schoolProject\\Diary-manger\\Diary-manger\\noteImagePath";

        Files.createDirectories(Paths.get(coverUploadDir));
        Files.createDirectories(Paths.get(imageUploadDir));

        System.out.println("tags=[" + tags + "]");
        // 校验 noteId 是否匹配
        if (noteId == null || !noteId.equals(noteBean.getNoteId())) {
            return new ResponseEntity<>("Invalid note ID", HttpStatus.BAD_REQUEST);
        }

        // 处理封面图片上传
        if (coverFile != null && !coverFile.isEmpty()) {
            try {
                // 获取文件名并构建保存路径
                String fileName = StringUtils.cleanPath(coverFile.getOriginalFilename());
                Path path = Paths.get(coverUploadDir, fileName);
                // 保存文件到指定路径
                Files.copy(coverFile.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
                // 构建相对文件下载URI
                String relativeFileDownloadUri = "/noteCoverPath/" + fileName;
                // 设置封面图片链接到noteBean
                noteBean.setCoverLink(relativeFileDownloadUri);
            }catch (IOException e) {
                e.printStackTrace();
                return new ResponseEntity<>("笔记修改失败！", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        // 处理笔记中的图片上传
        StringBuilder imageLinks = new StringBuilder();
        if (imagesLink != null && !imagesLink.isEmpty()) {
            for (MultipartFile image : imagesLink) {
                if (!image.isEmpty()) {
                    try {
                        // 获取文件名并构建保存路径
                        String fileName = StringUtils.cleanPath(image.getOriginalFilename());
                        Path path = Paths.get(imageUploadDir, fileName);

                        // 保存文件到指定路径
                        Files.copy(image.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);

                        // 构建相对文件下载URI
                        String relativeFileDownloadUri = "/noteImagePath/" + fileName;

                        // 拼接图片链接
                        if (imageLinks.length() > 0) {
                            imageLinks.append(",");
                        }
                        imageLinks.append(relativeFileDownloadUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return new ResponseEntity<>("笔记图片上传失败！", HttpStatus.INTERNAL_SERVER_ERROR);
                    }
                }
            }
            // 更新笔记对象中的图片链接字段
            noteBean.setImageLink(imageLinks.toString());
        }

        // 把 tags 设置到 noteBean
        if (tags != null) {
            noteBean.setTags(tags);  // 确保 NoteBean 有 setTags(List<String> tags) 方法
        }
        // 调用服务层更新笔记
        boolean isUpdated = noteService.updateNote(noteBean);
        if (isUpdated) {
            System.out.println("笔记修改成功！");
            return new ResponseEntity<>("笔记修改成功！", HttpStatus.OK);
        } else {
            return new ResponseEntity<>("笔记修改失败！", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping(value = "/selectIsPublicNoteAll")
    public ResponseEntity<List<NoteBean>> getIsPublicNoteAll(){
        try {
            // 调用服务层方法获取所有公开的日记
            return noteService.getIsPublicNoteAll();
        } catch (Exception e) {
            // 捕获异常并返回错误响应
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.emptyList());
        }
    }


}
